import React from 'react';
import { Drawer, Badge, Button, List, message, notification, Spin, Tooltip } from 'antd';
import './style.scss';
import { BellOutlined, WarningOutlined, DeleteOutlined, RightOutlined } from '@ant-design/icons';
import InfiniteScroll from 'react-infinite-scroller';
import { JSONObject } from 'admin/schema/common';
import { AlarmListInfo } from 'admin/schema/Alarm';
import { getSocket } from 'servers/socket';
import { AlarmMsg } from 'admin/schema/SocketMessage';

import { getAlarmFocusCount, modifyAlarm, deleteAlarm, getAlarmList } from 'admin/servers/servers';

interface IProp {
  fn: any; // 暴露父级方法
  visible: boolean; // 抽屉显示隐藏
}

interface IState {
  current: number;
  pageSize: number;
  newsCount: number;
  count: number;
  loading: boolean;
  hasMore: boolean;
  datalist: AlarmListInfo[];
}

class AlarmModal extends React.Component<IProp, IState> {
  constructor(prop: IProp) {
    super(prop);
    this.state = {
      current: 1,
      pageSize: 10,
      newsCount: 0,
      count: 0,
      loading: false,
      hasMore: false,
      datalist: [],
    };
  }
  componentDidMount() {
    this.addSocketEvent();
    // 告警总数获取
    this.loadNewsCount();
  }
  componentWillUnmount = () => {
    this.removeSocketEvent();
    this.setState = (state, callback) => {
      return;
    };
  };
  /**
   * 加载列表数据
   */
  private loadMoreData() {
    console.group('%c%s', 'color:blue', 'loading数据===============告警组件>>>>');
    console.groupEnd();
    const { datalist, current, pageSize, count } = this.state;
    console.log(datalist, '页面的datalist'); //查看数据是否已经改变
    // count非0时，datalist超过总条数，禁止加载
    console.log(count, '页面的count');
    if (count === 0) {
      console.log('1.初始化时；2.没有告警；');
      // 1.初始化时；2.没有告警；
      this.setState({
        loading: false,
        hasMore: false,
        datalist: [],
        current: 1,
      });
    }
    if (count > 0 && datalist?.length >= count) {
      // 有告警--已全部显示到列表中
      message.info('全部加载完成');
      console.log('全部加载完成');
      this.setState({
        loading: false,
        hasMore: false,
      });
      return;
    }
    // 有告警--部分显示到列表中--继续请求
    this.setState({
      loading: true,
      hasMore: true,
    });
    getAlarmList({
      pageNo: current,
      pageSize: pageSize,
    })
      .then(res => {
        this.setState({
          loading: false,
        });

        if (res.code === 0) {
          // console.log(
          //   res.data,
          //   `success--✅---后端返回--第${current}页--数据,总记录数${res.count}`
          // );
          if (!res.count) {
            // 告警数量为0
            return;
          }
          this.setState(
            {
              current: current + 1,
              count: res.count || 0,
              datalist: datalist.concat(res.data), //拼接每次加载的数据
            }
            // ,
            // () => {
            //   console.log(this.state.datalist, "拼接后datalist"); //查看数据是否已经改变
            // }
          );
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
        this.setState({
          loading: false,
        });
      });
  }
  /**
   * 取消新告警标志，红点消失
   */
  private handleFocus(alarmId: string) {
    console.log('hover--红点消失');
    modifyAlarm(alarmId)
      .then(res => {
        if (res.code === 0) {
          // 更新datalist
          const { datalist } = this.state;
          datalist.forEach((obj: any) => {
            if (obj.alarmId === alarmId) {
              obj.isFocus = 0;
            }
          });
          this.setState({
            datalist: [...datalist],
          });
          // 更新告警icon的总数
          this.loadNewsCount();
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  /**
   * 删除全部告警
   */
  private deleteAllTask() {
    deleteAlarm()
      .then(res => {
        if (res.code === 0) {
          message.success('删除成功');
          this.setState({
            count: 0,
            current: 1,
          });
          // 重新加载组件数据
          this.loadMoreData();
          this.loadNewsCount();
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  /**
   * 打开抽屉
   */
  public openAlarmDrawer() {
    this.props.fn('alarm');

    this.loadMoreData();
  }
  /**
   * 关闭抽屉
   */
  public closeAlarmDrawer() {
    this.props.fn();
    this.setState({
      current: 1,
      datalist: [],
    });
  }

  /**
   * 数字不够2位补0
   */
  public add0(m: number) {
    return m < 10 ? '0' + m : m;
  }
  /**
   * 根据时间戳，如果是今天显示hh:ss，非今天显示mm:dd
   */
  public getTimeByStamp(stamp: number) {
    // 后端：stamp为13位，后三位为0
    // if (stamp.toString().length === 10) {
    //   stamp = parseInt(stamp.toString() + "000");
    // }
    // debugger;
    const daytime = new Date(stamp); // 时间戳转换为date时间格式
    // console.log(daytime, "-时间", new Date());
    const today = new Date().toDateString(); // 获取今天的日期
    const day = daytime.toDateString(); // 获取日期
    // 比较日期
    if (day === today) {
      // 今天
      const h = daytime.getHours();
      const mm = daytime.getMinutes();
      return this.add0(h) + ':' + this.add0(mm);
    } else {
      // 非今天
      const m = daytime.getMonth() + 1;
      const d = daytime.getDate();
      return this.add0(m) + '-' + this.add0(d);
    }
  }
  /**
   * 获取新告警总数
   */
  private loadNewsCount() {
    getAlarmFocusCount()
      .then(res => {
        if (res.code === 0) {
          this.setState({
            newsCount: res.count || 0,
          });
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }
  private addSocketEvent(): void {
    console.log('告警消息推送事件-事件-start');
    getSocket().addEvent('alarmContentEvent', (data: JSONObject) => {
      // 接收到消息,文件准备好
      console.log(data, '告警消息推送----');

      data = data as AlarmMsg;
      const { content } = data;
      // 告警中心总数-更新
      this.loadNewsCount();
      if (this.props.visible) {
        // 弹窗开启时：列表数据-更新
        this.setState(
          {
            current: 1,
            datalist: [],
          },
          () => {
            this.loadMoreData();
          }
        );
      }
      // 弹窗，文件准备好，可以告警
      const close = () => {
        console.log('告警文件消息关闭');
      };
      const handleClick = () => {
        // 打开告警消息抽屉
        notification.close(key);
        this.openAlarmDrawer();
      };
      // 告警文件生成后-快捷告警通知-显示
      const key = `openAlarmDrawer${Date.now()}`;

      notification.open({
        message: null,
        description: `${content}`,
        icon: <WarningOutlined style={{ fontSize: 30, color: '#f2211b' }} />,
        top: 55,
        key,
        onClose: close,
        className: 'custom-alarm-notification',
        duration: 5,
        style: {
          width: 320,
        },
        onClick: handleClick,
      });
    });
  }
  /** 卸载socket事件*/
  private removeSocketEvent() {
    console.log('告警消息推送事件->>>>socket事件-删除');
    const socket = getSocket();
    socket.removeEvent(['alarmContentEvent']);
  }
  render() {
    const { newsCount, loading, hasMore, datalist, count } = this.state;
    return (
      <div className="layout-header-alarm">
        <Badge size="small" count={newsCount} title="新消息">
          <Tooltip title="告警消息">
            <Button
              className="alarm-btn"
              type="primary"
              shape="circle"
              icon={<BellOutlined />}
              onClick={() => {
                if (this.props.visible) {
                  this.closeAlarmDrawer();
                } else {
                  this.openAlarmDrawer();
                }
              }}
            />
          </Tooltip>
        </Badge>
        {this.props.visible && (
          <div className="alarm-wrapper">
            <Drawer
              className="alarm-drawer"
              title="告警消息"
              placement="right"
              width={400}
              closable={true}
              closeIcon={<RightOutlined style={{ color: '#1890ff' }} />}
              mask={true}
              onClose={() => {
                this.closeAlarmDrawer();
              }}
              visible={this.props.visible || false}
              footer={false}
              getContainer={false}
              style={{ position: 'absolute' }}
            >
              <Tooltip placement="bottomRight" title={count ? '删除全部' : ''}>
                <Button
                  disabled={!count}
                  className="delete-all-btn"
                  type="link"
                  onClick={() => {
                    this.deleteAllTask();
                  }}
                >
                  <DeleteOutlined style={{ fontSize: 20 }} />
                </Button>
              </Tooltip>
              {/* 滚动加载列表 */}
              <div
                className="demo-infinite-container"
                style={{
                  height: 'calc(100% - 5px)',
                  overflow: 'auto',
                }}
              >
                <InfiniteScroll
                  initialLoad={false}
                  pageStart={0}
                  loadMore={() => {
                    this.loadMoreData();
                  }}
                  threshold={1}
                  hasMore={!loading && hasMore}
                  useWindow={false} //****将滚动侦听器添加到窗口，或者添加组件的parentNode****
                >
                  {!loading && (
                    <List
                      dataSource={datalist}
                      renderItem={(item: AlarmListInfo) => (
                        <List.Item
                          className={item.isFocus ? 'isNew' : ''}
                          onMouseEnter={() => {
                            if (!item.isFocus) {
                              // 非新告警
                              return false;
                            }
                            this.handleFocus(item.alarmId);
                          }}
                          key={item.alarmId}
                          actions={[
                            <span key={'span' + item.alarmId}>
                              {this.getTimeByStamp(item.time)}
                            </span>,
                          ]}
                        >
                          <List.Item.Meta
                            className="list-item-meta"
                            avatar={
                              <div>
                                <Badge dot={item.isFocus ? true : false}></Badge>
                              </div>
                            }
                            title={
                              <span>
                                {/* 文件名{item.alarmId} */}
                                {/* 上面的id调试用 */}
                                {item.content}
                              </span>
                            }
                            description={null}
                          />
                        </List.Item>
                      )}
                    ></List>
                  )}
                  <Spin spinning={loading && hasMore} size="large"></Spin>
                </InfiniteScroll>
                {loading && hasMore && <div className="loading-txt">加载中</div>}
                {count > 0 && !loading && !hasMore && <div className="footer-txt">已无更多</div>}
              </div>
            </Drawer>
          </div>
        )}
      </div>
    );
  }
}
export default AlarmModal;
